const express = require('express')
const path = require('path')
const userManage = require(path.join(__dirname, '../../models/music_db/user_manage.js'))
// 用户等级集合
const vipManage = require(path.join(__dirname, '../../models/music_db/vip_grade.js'))
//  用户评论集合
const commentManage = require(path.join(__dirname, '../../models/music_db/comment.js'))
const util = require('../../utils/index')

const router = express.Router()

const SUCCESS = '00000'
const ERROR = '99998'
const NOLOGIN = '99996'
function handData(value) {
  return JSON.parse(JSON.stringify(value))
}

// 获取会话信息
router.get('/music/user-infor', (request, response, next) => {
  if (request.session.userNo) {
    userManage
      .aggregate([
        {
          $lookup: {
            from: 'vip_grades',
            localField: 'userNo',
            foreignField: 'userNo',
            as: 'vipGrade'
          }
        },
        { $unwind: '$vipGrade' },
        { $match: { userNo: request.session.userNo } },
        { $project: { _id: 0, password: 0 } }
      ])
      .then(list => {
        if (list.length) {
          // 用户存才
          response.json({
            code: SUCCESS,
            data: list[0]
          })
        } else {
          // 用户不存在
          delete request.session.userNo
          response.json({
            code: NOLOGIN,
            data: null,
            msg: '未登录'
          })
        }
      })
      .catch(err => next())
  } else {
    response.json({
      code: NOLOGIN,
      data: null,
      msg: '未登录'
    })
  }
})

// 用户登录验证
router.post('/music/login', (request, response, next) => {
  let { account, password } = request.body
  userManage
    .findOne({ account, password })
    .then(value => {
      if (value) {
        // 设置session，确保能获取会话信息，自动登录
        request.session.userNo = value.userNo
        // let data = handData(value)
        // delete data.password
        response.json({
          code: SUCCESS,
          data: null
        })
      } else {
        next(['账号或密码错误', ERROR])
      }
    })
    .catch(err => next())
})
//退出登录
router.post('/music/logout', (request, response, next) => {
  if (delete request.session.userNo) {
    response.json({
      code: SUCCESS,
      data: null
    })
  } else {
    next(['登出失败'])
  }
})

// 修改手机号和密码
router.patch('/music/modify-password', async (request, response, next) => {
  if (request.session.userNo) {
    const { account, password } = request.body
    // 电话验证
    if (!util.phone(account)) return next(['电话号格式不正确', ERROR])
    // 密码验证
    // if (!util.password(password)) return next(['密码是6-18位的数字和字符', ERROR])
    userManage.updateOne({ id: request.session.userNo }, { account, password }).then(
      () => {
        response.json({
          code: SUCCESS,
          data: null
        })
      },
      () => {
        next(['更改失败'])
      }
    )
  } else {
    next(['未登录', NOLOGIN])
  }
})
// 编辑资料
router.patch('/music/edit-info', async (request, response, next) => {
  if (request.session.userNo) {
    const data = { ...request.body }
    userManage.updateOne({ userNo: request.session.userNo }, data).then(
      () => {
        response.json({
          code: SUCCESS,
          data: null
        })
      },
      () => {
        next(['更改失败'])
      }
    )
  } else {
    next(['未登录', NOLOGIN])
  }
})
// 编辑vip集合（、开通vip）
/**
 * 传参：
 * 增加经验值：无
 * 开通会员:
 * @param {Boolean}vip
 * @param {Date}vipEndTime
 * @param {Date}vipStartTime
 * 会员续费:
 * @param {Boolean}renewal
 * @param {Date}vipEndTime
 * @param {Date}vipStartTime
 */
/*听完1/3加10点经验，2/3加20,3/3加30。这个接口就只调一次加10点经验,vip加15*/
router.put('/music/add-experience', (request, response, next) => {
  const userNo = request.session.userNo
  const openVip = Boolean(request.body.vip) // true或false, 有此字段则是开通会员
  const renewal = Boolean(request.body.renewal) // true或false, 有此字段则是续费
  const add = 10,
    vipadd = 15,
    range = 100
  if (!userNo) {
    return response.json({
      code: NOLOGIN,
      data: null,
      msg: '未登录'
    })
  }
  vipManage
    .findOne({ userNo })
    .then(value => {
      if (!value) return Promise.reject(['用户不存在', ERROR])
      let params = null

      function increase(addsize) {
        if (value.nowExperience + addsize >= value.fullExperience) {
          // 升级
          return {
            vipGrade: value.vipGrade + 1,
            nowExperience: value.nowExperience + addsize - value.fullExperience,
            fullExperience: (value.vipGrade + 1) * range
          }
        } else {
          return {
            nowExperience: value.nowExperience + addsize
          }
        }
      }

      if (openVip) {
        // 开通会员
        if (value.vip) return Promise.reject(['此用户已经是会员了', ERROR])
        params = util.regFn(['vip', 'vipEndTime', 'vipStartTime'], { reqParams: request.body, query: false })
      } else if (renewal) {
        // 续费会员
        params = util.regFn(['vipEndTime', 'vipStartTime'], { reqParams: request.body, query: false })
        params.vip = true // 续费后直接变为true
      } else if (value.vip) {
        // vip加经验值
        params = increase(vipadd)
      } else {
        // 非vip加经验值
        params = increase(add)
      }
      return vipManage.findOneAndUpdate({ userNo }, params, { new: true })
    })
    .then(data => {
      response.json({
        code: SUCCESS,
        data: data
      })
    })
    .catch(err => next(err))
})

/**
 * 传参：
 * @param {string} commentNo
 */
// 给评论点赞
router.put('/music/like-comment/:commentNo', (request, response, next) => {
  if (!request.session.userNo) return next(['未登录', NOLOGIN])
  commentManage
    .updateOne({ commentNo: request.params.commentNo }, { $inc: { likeNum: 1 } })
    .then(() => {
      return response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(err => next(err))
})
/**
 * 传参：
 * @param {string} modeNo
 */
// 查询评论
router.get('/music/comment/:modeNo', (request, response, next) => {
  const params = {}
  if (request.params.modeNo.slice(0, 2) == 'GQ') {
    params.songNo = request.params.modeNo
  } else if (request.params.modeNo.slice(0, 2) == 'GS') {
    params.songerNo = request.params.modeNo
  } else if (request.params.modeNo.slice(0, 2) == 'GD') {
    params.songlistNo = request.params.modeNo
  } else {
    return next(['模块编号没传', ERROR])
  }
  commentManage
    .aggregate([
      {
        $lookup: {
          from: 'user_manages',
          localField: 'userNo',
          foreignField: 'userNo',
          as: 'userinfor'
        }
      },
      { $unwind: '$userinfor' },
      { $match: params }, // 这个查询必有的
      {
        $match: util.regFn(['nickname', 'content'], { reqParams: request.query })
      }
    ])
    .then(data => {
      return response.json({
        code: SUCCESS,
        data
      })
    })
    .catch(err => next(err))
})
module.exports = router
